#include "global.h"
#include "modbus.h"
#include "device.h"
#include "infoblock.h"
#include "string.h"

#ifndef _STR
#define __STR(x)                #x
#define _STR(x)                 __STR(x)
#endif
#define REVISION_STRING         "V" _STR(APP_FW_VERSION_HIGH) "." _STR(APP_FW_VERSION_LOW) " " __DATE2__

#define OBJECT_VENDOR_NAME      0x00
#define OBJECT_PRODUCT_CODE     0x01
#define OBJECT_REVISION         0x02

#define OBJECT_COUNT            3

typedef struct DEVICE_OBJECT
{
    uchar id;
    uchar *val;
} DEVICE_OBJECT;

DEVICE_OBJECT code object[OBJECT_COUNT] =
{
    OBJECT_VENDOR_NAME,     "Zonci",
    OBJECT_PRODUCT_CODE,    "0003",
    OBJECT_REVISION,        REVISION_STRING
};

void Read_Identification()
{
    uchar n, len;

    // 查找匹配的ID
    for(n = 0; n < OBJECT_COUNT; ++n)
        if (object[n].id == uart0_buf[4])
            break;

    if (n >= OBJECT_COUNT)
        n = 0;

    // 单个访问时, 指定的ID不存在
    if (uart0_buf[3] == 4 && object[n].id != uart0_buf[4])
    {
        Exception_Response(ILLEGAL_DATA_ADDRESS);
        return;
    }

    uart0_buf[4] = 0x83;    // 符合级
    uart0_buf[5] = 0x00;    // 更多数据
    uart0_buf[6] = 0x00;    // 下一对象ID
    uart0_buf[7] = uart0_buf[3] == 4 ? 1 : OBJECT_COUNT;    // 对象数量

    uart0_len = 8;
    for(; n < OBJECT_COUNT; ++n)
    {
        len = strlen(object[n].val);
        if (uart0_len + len + 4 >= UART0_BUF_SIZE)
        {
            uart0_buf[5] = 0xFF;            // 更多数据
            uart0_buf[6] = object[n].id;    // 下一对象ID
            break;
        }

        uart0_buf[uart0_len++] = object[n].id;
        uart0_buf[uart0_len++] = len;
        strcpy(uart0_buf+uart0_len, object[n].val);
        uart0_len += len;
    }

    Response();
}
